/**
 * @Title: LeaveOutDetailActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月20日 下午10:47:24
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.LeaveOutBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.utils.DataUtils;

/**
 * @ClassName: LeaveOutDetailActivity
 * @Description: 请销假详情
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月20日 下午10:47:24
 */
public class LeaveOutDetailActivity extends BaseActivity {

	private static final String TAG = "LeaveOutDetailActivity";
	public static final int CHOOSE_PHOTO_REQUEST_OK = 1001;
	private static final int mChooseImageCount = 1;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;

	@BindView(id = R.id.tv_id)
	private TextView mIdTextView;
	@BindView(id = R.id.tv_name)
	private TextView mNameTextView;
	@BindView(id = R.id.tv_organId)
	private TextView mOrganIdTextView;
	@BindView(id = R.id.tv_organ)
	private TextView mOrganTextView;
	@BindView(id = R.id.tv_signType)
	private TextView mSignTypeTextView;
	@BindView(id = R.id.tv_time)
	private TextView mTimeTextView;
	@BindView(id = R.id.tv_isCancel)
	private TextView mIsCancelTextView;
	@BindView(id = R.id.leave_out_detail_button_ask_leave, click = true)
	private Button mAskLeaveButton;
	@BindView(id = R.id.leave_out_detail_button_sick_leave, click = true)
	private Button mSickLeaveButton;

	private AppContext mAppContext;
	private KJDB mKjdb;
	private LeaveOutBean mLeaveOutBean;
	private int mSignType = 1;// 默认请假签到
	private List<String> mCacheCheckImages = new ArrayList<String>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_leave_out_detail);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		super.initWidget();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		super.initData();
		mAppContext = (AppContext) getApplicationContext();
		mKjdb = mAppContext.getKjdb();

		Intent intent = getIntent();
		if (intent != null) {
			mLeaveOutBean = (LeaveOutBean) intent
					.getSerializableExtra("LeaveOutBean");
			String name = mLeaveOutBean.getName();
			mTitleTextView.setText(name);
			mIdTextView.setText(mLeaveOutBean.getRymcid());
			mNameTextView.setText(name);
			mOrganIdTextView.setText(mLeaveOutBean.getOrganid());
			mOrganTextView.setText(mLeaveOutBean.getOrgan());
			mSignTypeTextView.setText(DataHelper
					.getContentBySignType(mLeaveOutBean.getSignType()));
			mTimeTextView.setText(mLeaveOutBean.getTime());
			mIsCancelTextView.setText(DataHelper
					.getContentByIsCancel(mLeaveOutBean.getIsCancel()));
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view
	 * .View)
	 */
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(this);
			break;
		case R.id.leave_out_detail_button_ask_leave:
			// TODO 没有指纹或者打卡的签到
			mSignType = 1;
			choosePhoto();
			break;
		case R.id.leave_out_detail_button_sick_leave:
			// TODO 没有指纹或者打卡的签到
			mSignType = 3;
			choosePhoto();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "---> onActivityResult requestCode:" + requestCode
				+ ",resultCode:" + resultCode);
		if (requestCode == CHOOSE_PHOTO_REQUEST_OK && resultCode == 1001) {
			saveDate();
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					String path = mCacheCheckImages.get(0);
					Message message = new Message();
					message.what = 100;
					message.obj = path;
					savePhoto(path);
				}

			}
		}
	}

	private Handler mSavePhotoHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 100:
				String path = (String) msg.obj;
				savePhoto(path);
				break;

			default:
				break;
			}
		};
	};

	// 把选取的图片保存到数据库
	private void savePhoto(String photoPath) {
		Log.i(TAG, "---> savePhoto photoPath:" + photoPath);
		Log.i(TAG, "---> savePhoto :" + mLeaveOutBean);
		if (!StringUtils.isEmpty(photoPath)) {
			ImageOrAudioBean bean = DataHelper.getImageOrAudioBeanInfoByPath(
					this, photoPath,1);
			bean.setServiceId(5);
			bean.setSignType(String.valueOf(mSignType));
			bean.setParentId(mLeaveOutBean.getId());
			Log.i(TAG, "---> savePhoto " + bean);
			mKjdb.save(bean);
		} else {
			Toast.makeText(this, "选取图片失败", Toast.LENGTH_SHORT).show();
		}
	}

	// 图片
	private void choosePhoto() {
		if (mLeaveOutBean != null) {
			// TODO 弹出选择照片
			String id = mLeaveOutBean.getId();
			boolean flag = isSuccessSign(id, mSignType);
			if (!flag) {
				takePhoto();
			}
		} else {
			Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
		}
	}

	// 保存签到信息到数据库
	private void saveDate() {
		if (mLeaveOutBean != null) {
			LeaveOutBean bean2 = new LeaveOutBean();
			bean2.setId(mLeaveOutBean.getId());
			bean2.setTime(DataUtils.converDatLongToString(
					System.currentTimeMillis(), DateFormat.DATE_YMD_HMS));
			bean2.setSignFlag("0");
			bean2.setRymcid(mLeaveOutBean.getRymcid());
			bean2.setName(mLeaveOutBean.getName());
			bean2.setPhotoUrl(mLeaveOutBean.getPhotoUrl());
			bean2.setSignType(String.valueOf(mSignType));
			bean2.setIsCancel(mLeaveOutBean.getIsCancel());
			bean2.setIsCancelLeave(mLeaveOutBean.getIsCancelLeave());
			bean2.setLeaveId(mLeaveOutBean.getLeaveId());
			bean2.setOrganid(mLeaveOutBean.getOrganid());
			bean2.setOrgan(mLeaveOutBean.getOrgan());
			bean2.setState(1);
			// TODO 保存成功之后需要提示是否拍照
			mKjdb.save(bean2);
			String tip = "请假签到成功";
			if (mSignType != 1) {
				tip = "销假签到成功";
			}
			Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
			KJActivityManager.create().finishActivity(this);
		} else {
			Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
		}

	}

	private void takePhoto() {
		// 拍照
		new AlertDialog.Builder(this).setTitle("拍照").setMessage("是否进行拍照？")
				.setCancelable(true)
				.setPositiveButton("确定", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent takePicture = new Intent(
								LeaveOutDetailActivity.this,
								ChoosePhotoActivity.class);
						takePicture.putExtra(
								ChoosePhotoActivity.CHOOSE_PHOTO_COUNT,
								mChooseImageCount);
						startActivityForResult(takePicture,
								DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
					}

				}).setNegativeButton("取消", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						saveDate();
						dialog.dismiss();
					}

				}).create().show();

	}

	// 判断是否签到过
	private boolean isSuccessSign(String id, int signType) {
		try {
			List<LeaveOutBean> beans = mKjdb.findAllByWhere(LeaveOutBean.class,
					" signType = '" + signType + "' and id = '" + id + "'");
			if (beans != null && !beans.isEmpty()) {
				LeaveOutBean bean = beans.get(0);
				if (bean != null) {
					String toast = "";
					if (signType == 1) {
						toast = "已经请假签到";
					} else if (signType == 3) {
						toast = "已经销假签到";
					}
					Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
					return true;

				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

}
